package com.zc58s.springbootmqtt.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @author : fujc-dev@qq.com
 * @created : 2022/9/21 11:56
 */

public class MqttSubscribeSample {

    public static final String content = "{ \"sn\":3, \"wbtksn\":\"WTZ25100051000000M8T9000\", \"cloudsn\":\"cloud001\", \"type\":\"all\", \"codearr\":[ \"C_1001_VR_0000\", \"C_1001_VR_0001\" ] }";
    public static final String topic_res = "WSN/CSN/sub/data/res";
    public static final String topic_req = "CSN/WSN/sub/data/req";
    public static final String HOST = "tcp://111.198.38.198:7039";
    private static final String userName = "test01";
    private static final String passWord = "123456789";
    private static final String clientId = "kggs003";
    private static final int qos = 1;

    public static void main(String[] args) {

        MemoryPersistence persistence = new MemoryPersistence();
        try {
            MqttClient sampleClient = new MqttClient(HOST, clientId, persistence);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setKeepAliveInterval(2);
            // 设置回调
            sampleClient.setCallback(new MQTTCallback());
            MqttTopic topic = sampleClient.getTopic(topic_res);
            //setWill方法，如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
            //options.setWill(topic, "close".getBytes(), 2, true);
            sampleClient.connect(options);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            sampleClient.publish(topic_req, message);
            int[] Qos = {0, 0, 0};
            String[] topicFilters = {topic_res, "WSN/CSN/pub/data/req", "WSN/CSN/repub/data/req"};
            sampleClient.subscribe(topicFilters, Qos);
            System.out.println("Message subscribe");
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }

}
